package com.item.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import org.apache.commons.lang.StringUtils;

import com.base.CoreConstants;
import com.base.support.PropertySupport;
import com.base.util.MyOssClient;
import com.item.scraputils.fetcher.BaseFetcher;

/**
 * 小文件操作类	2014-7-18
 * @author yjh
 *
 */
public class FileAccessor {
	private static String BUCKET_NAME_WEB = PropertySupport.getProperty("oss.webfile");
	/**
	 * 读取所有内容，文件不存在返回null
	 * @param filename
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static String readAll(String key, String encoding) throws Exception {
		StringBuilder sb = new StringBuilder();
		if(key.startsWith("/")) //阿里云不能以/开头
			key = key.substring(1);
		InputStream in = MyOssClient.getObjectStream(key, BUCKET_NAME_WEB);
		BufferedReader br = null;
		if(in != null) {
			try {
				char[] buf = new char[1024];
				br = new BufferedReader(new InputStreamReader(in, encoding));
				int len = 0;
				while((len = br.read(buf)) != -1) {
					sb.append(buf, 0, len);//不要忘了每次都要读取len，否则最后会有问题
				}
			} finally {
				if(br != null)
					br.close();
				if(in != null)
					in.close();
			}
			
		} else {
			return null;
		}
		return sb.toString();
	}
	
	/**
	 * 写入所有内容
	 * @param key
	 * @param content
	 * @param encoding
	 * @throws Exception
	 */
	public static void writeAll(String key, String content, String encoding) throws Exception {
		if(StringUtils.isNotBlank(content)) {
			if(key.startsWith("/")) //阿里云不能以/开头
				key = key.substring(1);
			byte[] data = content.getBytes(encoding);
			MyOssClient.putObject(key, data, BUCKET_NAME_WEB);	//写入阿里云
		}
	}
	
	/**
	 * 写入所有字节数组，为图片等非文本信息提供
	 * @param key
	 * @param content
	 * @param encoding
	 * @throws Exception
	 */
	public static void writeAllBytes(String key, byte[] data) throws Exception {
		if(data != null) {
			if(key.startsWith("/"))
				key = key.substring(1);
			MyOssClient.putObject(key, data, BUCKET_NAME_WEB);	//写入阿里云
		}
	}
	
	/**
	 * 获取网络文件写入阿里云，这里用在服务器文件系统缓存，以防止网络资源content-length缺失的情况
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getNetFile(String url) throws Exception {
		BaseFetcher fetcher = new BaseFetcher();
		String key = new StringBuilder("tempimg/").append(System.currentTimeMillis()).append(".jpg").toString();
		File file = new File(CoreConstants.FILE_PATH + "/" + key);
		
		byte[] data = fetcher.transVerifyImgToArray(url, file);
		
		writeAllBytes(key, data);
		
		if(file.exists())
			file.delete();
		
		return key;
	}
	
	public static void deleteFile(String key) {
		if(key.startsWith("/")) //阿里云不能以/开头
			key = key.substring(1);
		MyOssClient.deleteObject(key, BUCKET_NAME_WEB);
	}
}
